<?php

declare ( strict_types = 1 );
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf-cloud/hyperf/blob/master/LICENSE
 */

namespace App\Common\Model\Origin;

use App\Common as com;
use Hyperf\DbConnection\Model\Model;

/**
 * @method static $this create()
 */
abstract class OriginBase extends Model {
	// const CREATED_AT = 'creation_date || null';
	// const UPDATED_AT = 'last_update || null';
	protected ?string $dateFormat = 'U';

	/**
	 * 判断数据是否存在
	 * @param string | array $where DB::where查询条件（如果查询字段为[id]，则可以直接输入要查询值）
	 * @return bool [false]不存在 [true]存在
	 */
	public static function isExist( $where ):bool {
		if( ! is_array( $where ) ){
			$where = [ 'id' => $where ];
		}
		return self::isExistToID( $where ) ? true : false;
	}

	/**
	 * 判断数据是否存在，存在则返回主键id
	 * @param string | array $where DB::where查询条件（如果查询字段为[id]，则可以直接输入要查询值）
	 * @return int|null [null]不存在 [>0]存在，并返回主键id
	 */
	public static function isExistToID( $where ):?int {
		if( ! is_array( $where ) ){
			$where = [ 'id' => $where ];
		}
		$value = self::query()->where( $where )->value( 'id' );
		if( is_numeric( $value ) && $value > 0 ){
			return $value;
		} else{
			if( $value === null ){
				return null;
			} else{
				throw com\Lib\Err\Exception::makeOfNew( '', com\Lib\Err\Code::$sysAssertError );
			}
		}
	}

	/**
	 * Create a new Base model instance.
	 * @param array $attributes
	 * @return \Hyperf\Utils\HigherOrderTapProxy|mixed
	 */
	public static function createX( array $attributes = [] ) {
		$model = new static();
		return tap( $model->query()->newModelInstance(), function ( \Hyperf\Database\Model\Model $instance ) use ( $attributes ) {
			foreach( $attributes as $key => $value ){
				$instance->setAttribute( $key, $value );
			}
			$instance->save();
		} );
		/*		$model = new static();
				foreach ($attributes as $key => $value) {
					$model->setAttribute( $key, $value );
				}
				//
				return $model->save();*/
	}

	public function getAttributes():array {
		return $this->attributes;
	}
}